/*
 * @Author: xuhy
 * @Date: 2022-04-03 16:19:21
 * @LastEditTime: 2022-04-26 15:29:43
 * @LastEditors: Please set LastEditors
 * @Description: 配置路由相关规则
 * @FilePath: \vue_shop\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
// 采用vue-router开箱即用的动态导入
const LoginUser = () => import('../components/LoginUser')
const HomeAccess = () => import('../components/HomeAccess')
const WelcomePage = () => import('../components/WelcomePage')
const UsersList = () => import('../components/user/UsersList')
const RightsList = () => import('../components/power/RightsList')
const RolesList = () => import('../components/power/RolesList')
const GoodsCate = () => import('../components/goods/GoodsCate')
const GoodsParams = () => import('../components/goods/GoodsParams')
const GoodsList = () => import('../components/goods/GoodsList')
const GoodsAdd = () => import('../components/goods/GoodsAdd')
const OrderList = () => import('../components/order/OrderList')
const DataReport = () => import('../components/report/DataReport')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: LoginUser },
    {
      path: '/home',
      component: HomeAccess,
      // 路由重定向
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: WelcomePage },
        { path: '/users', component: UsersList },
        { path: '/rights', component: RightsList },
        { path: '/roles', component: RolesList },
        { path: '/categories', component: GoodsCate },
        { path: '/params', component: GoodsParams },
        { path: '/goods', component: GoodsList },
        { path: '/goods/add', component: GoodsAdd },
        { path: '/orders', component: OrderList },
        { path: '/reports', component: DataReport }
      ]
    }
  ]
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from从哪个路径跳转
  // next是一个函数，表示放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})
export default router
